/**
 * @file sys_arch.c
 * @author zdk
 * @brief LwIP操作系统模拟层实现，基于rt-thread nano
 * @version 0.1
 * @date 2021-08-02
 * 
 * BSD 3-Clause License
 * 
 * Copyright (c) 2021, water_zhang
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * 
 * * Redistributions of source code must retain the above copyright notice, this
 *   list of conditions and the following disclaimer.
 * 
 * * Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 * 
 * * Neither the name of the copyright holder nor the names of its
 *   contributors may be used to endorse or promote products derived from
 *   this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * 
 * 实现线程、信号量、邮箱、互斥锁等操作接口
 * 
 */

#include "sys_arch.h"
#include "lwip/def.h"
#include "lwip/err.h"
#include "lwip/sys.h"

/**
 * sys_init() must be called before anything else.
 * Initialize the sys_arch layer.
 */
void sys_init(void)
{
    /* 没有事做 */
}

/* Semaphore functions: */

/**
 * @ingroup sys_sem
 * Create a new semaphore
 * Creates a new semaphore. The semaphore is allocated to the memory that 'sem'
 * points to (which can be both a pointer or the actual OS structure).
 * The "count" argument specifies the initial state of the semaphore (which is
 * either 0 or 1).
 * If the semaphore has been created, ERR_OK should be returned. Returning any
 * other error will provide a hint what went wrong, but except for assertions,
 * no real error handling is implemented.
 *
 * @param sem pointer to the semaphore to create
 * @param count initial count of the semaphore
 * @return ERR_OK if successful, another err_t otherwise
 */
err_t sys_sem_new(sys_sem_t *sem, u8_t count)
{
    LWIP_ASSERT(("sem != NULL"), sem);

    *sem = rt_sem_create("lwip_sem", count, RT_IPC_FLAG_PRIO);
    if (NULL == *sem)
    {
        LWIP_DEBUGF(NETIF_DEBUG, ("sem create fail.\r\n"));
        return ERR_MEM;
    }
    return ERR_OK;
}

/**
 * @ingroup sys_sem
 * Signals a semaphore
 * @param sem the semaphore to signal
 */
void sys_sem_signal(sys_sem_t *sem)
{
    LWIP_ASSERT(("sem != NULL"), sem);

    if (RT_EOK != rt_sem_release(*sem))
    {
        LWIP_DEBUGF(NETIF_DEBUG, ("sem release fail.\r\n"));
    }
}

/**
 * @ingroup sys_sem
 *  Blocks the thread while waiting for the semaphore to be signaled. If the
 * "timeout" argument is non-zero, the thread should only be blocked for the
 * specified time (measured in milliseconds). If the "timeout" argument is zero,
 * the thread should be blocked until the semaphore is signalled.
 * 
 * The return value is SYS_ARCH_TIMEOUT if the semaphore wasn't signaled within
 * the specified time or any other value if it was signaled (with or without
 * waiting).
 * Notice that lwIP implements a function with a similar name,
 * sys_sem_wait(), that uses the sys_arch_sem_wait() function.
 * 
 * @param sem the semaphore to wait for
 * @param timeout timeout in milliseconds to wait (0 = wait forever)
 * @return SYS_ARCH_TIMEOUT on timeout, any other value on success
 */
u32_t sys_arch_sem_wait(sys_sem_t *sem, u32_t timeout)
{
    LWIP_ASSERT(("sem != NULL"), sem);

    if (0 != timeout)
    {
        if (RT_EOK != rt_sem_take(*sem, timeout))
        {
            return SYS_ARCH_TIMEOUT;
        }
        return ~SYS_ARCH_TIMEOUT;
    }
    else
    {
        if (RT_EOK != rt_sem_take(*sem, RT_WAITING_FOREVER))
        {
            return SYS_ARCH_TIMEOUT;
        }
        return ~SYS_ARCH_TIMEOUT;
    }
}

/**
 * @ingroup sys_sem
 * Deallocates a semaphore.
 * @param sem semaphore to delete
 */
void sys_sem_free(sys_sem_t *sem)
{
    LWIP_ASSERT(("sem != NULL"), sem);

    if (RT_EOK != rt_sem_delete(*sem))
    {
        LWIP_DEBUGF(NETIF_DEBUG, ("sem delete fail.\r\n"));
    }
}

/**
 * @ingroup sys_sem
 * Returns 1 if the semaphore is valid, 0 if it is not valid.
 * When using pointers, a simple way is to check the pointer for != NULL.
 * When directly using OS structures, implementing this may be more complex.
 * This may also be a define, in which case the function is not prototyped.
 */
int sys_sem_valid(sys_sem_t *sem)
{
    if (NULL != *sem)
    {
        return 1;
    }
    return 0;
}

/**
 * @ingroup sys_sem
 * Invalidate a semaphore so that sys_sem_valid() returns 0.
 * ATTENTION: This does NOT mean that the semaphore shall be deallocated:
 * sys_sem_free() is always called before calling this function!
 * This may also be a define, in which case the function is not prototyped.
 */
void sys_sem_set_invalid(sys_sem_t *sem)
{
    *sem = NULL;
}

/* Mailbox functions. */

/**
 * @ingroup sys_mbox
 * Creates an empty mailbox for maximum "size" elements. Elements stored
 * in mailboxes are pointers. You have to define macros "_MBOX_SIZE"
 * in your lwipopts.h, or ignore this parameter in your implementation
 * and use a default size.
 * If the mailbox has been created, ERR_OK should be returned. Returning any
 * other error will provide a hint what went wrong, but except for assertions,
 * no real error handling is implemented.
 * 
 * @param mbox pointer to the mbox to create
 * @param size (minimum) number of messages in this mbox
 * @return ERR_OK if successful, another err_t otherwise
 */
err_t sys_mbox_new(sys_mbox_t *mbox, int size)
{
    LWIP_ASSERT(("mbox != NULL"), mbox);

    *mbox = rt_mb_create("lwip_mbox", size, RT_IPC_FLAG_PRIO);
    if (NULL == *mbox)
    {
        LWIP_DEBUGF(NETIF_DEBUG, ("mbox create fail, size = %d\r\n", size));
        return ERR_MEM;
    }
    return ERR_OK;
}

/**
 * @ingroup sys_mbox
 * Post a message to an mbox - may not fail
 * -> blocks if full, only to be used from tasks NOT from ISR!
 * 
 * @param mbox mbox to posts the message
 * @param msg message to post (ATTENTION: can be NULL)
 */
void sys_mbox_post(sys_mbox_t *mbox, void *msg)
{
    LWIP_ASSERT(("mbox != NULL"), mbox);

    if (RT_EOK != rt_mb_send_wait(*mbox, (rt_ubase_t)msg, RT_WAITING_FOREVER))
    {
        LWIP_DEBUGF(NETIF_DEBUG, ("mbox send fail.\r\n"));
    }
}

/**
 * @ingroup sys_mbox
 * Try to post a message to an mbox - may fail if full.
 * Can be used from ISR (if the sys arch layer allows this).
 * Returns ERR_MEM if it is full, else, ERR_OK if the "msg" is posted.
 * 
 * @param mbox mbox to posts the message
 * @param msg message to post (ATTENTION: can be NULL)
 */
err_t sys_mbox_trypost(sys_mbox_t *mbox, void *msg)
{
    LWIP_ASSERT(("mbox != NULL"), mbox);

    if (RT_EOK != rt_mb_send(*mbox, (rt_ubase_t)msg))
    {
        LWIP_DEBUGF(NETIF_DEBUG, ("mbox try send fail.\r\n"));
        return ERR_MEM;
    }
    return ERR_OK;
}

/**
 * @ingroup sys_mbox
 * Try to post a message to an mbox - may fail if full.
 * To be be used from ISR.
 * Returns ERR_MEM if it is full, else, ERR_OK if the "msg" is posted.
 * 
 * @param mbox mbox to posts the message
 * @param msg message to post (ATTENTION: can be NULL)
 */
err_t sys_mbox_trypost_fromisr(sys_mbox_t *mbox, void *msg)
{
    return sys_mbox_trypost(mbox, msg);
}

/**
 * @ingroup sys_mbox
 * Blocks the thread until a message arrives in the mailbox, but does
 * not block the thread longer than "timeout" milliseconds (similar to
 * the sys_arch_sem_wait() function). If "timeout" is 0, the thread should
 * be blocked until a message arrives. The "msg" argument is a result
 * parameter that is set by the function (i.e., by doing "*msg =
 * ptr"). The "msg" parameter maybe NULL to indicate that the message
 * should be dropped.
 * The return values are the same as for the sys_arch_sem_wait() function:
 * SYS_ARCH_TIMEOUT if there was a timeout, any other value if a messages
 * is received.
 * 
 * Note that a function with a similar name, sys_mbox_fetch(), is
 * implemented by lwIP. 
 * 
 * @param mbox mbox to get a message from
 * @param msg pointer where the message is stored
 * @param timeout maximum time (in milliseconds) to wait for a message (0 = wait forever)
 * @return SYS_ARCH_TIMEOUT on timeout, any other value if a message has been received
 */
u32_t sys_arch_mbox_fetch(sys_mbox_t *mbox, void **msg, u32_t timeout)
{
    LWIP_ASSERT(("mbox != NULL"), mbox);
    LWIP_ASSERT(("msg != NULL"), msg);

    if (timeout != 0)
    {
        if (RT_EOK != rt_mb_recv(*mbox, (rt_ubase_t *)msg, timeout))
        {
            return SYS_ARCH_TIMEOUT;
        }
        else
        {
            return ~SYS_ARCH_TIMEOUT;
        }
    }
    else
    {
        if (RT_EOK != rt_mb_recv(*mbox, (rt_ubase_t *)msg, RT_WAITING_FOREVER))
        {
            return SYS_ARCH_TIMEOUT;
        }
        else
        {
            return ~SYS_ARCH_TIMEOUT;
        }
    }
}

/**
 * @ingroup sys_mbox
 * This is similar to sys_arch_mbox_fetch, however if a message is not
 * present in the mailbox, it immediately returns with the code
 * SYS_MBOX_EMPTY. On success 0 is returned.
 * To allow for efficient implementations, this can be defined as a
 * function-like macro in sys_arch.h instead of a normal function. For
 * example, a naive implementation could be:
 * \#define sys_arch_mbox_tryfetch(mbox,msg) sys_arch_mbox_fetch(mbox,msg,1)
 * although this would introduce unnecessary delays.
 * 
 * @param mbox mbox to get a message from
 * @param msg pointer where the message is stored
 * @return 0 (milliseconds) if a message has been received
 *         or SYS_MBOX_EMPTY if the mailbox is empty
 */
u32_t sys_arch_mbox_tryfetch(sys_mbox_t *mbox, void **msg)
{
    LWIP_ASSERT(("mbox != NULL"), mbox);
    LWIP_ASSERT(("msg != NULL"), msg);

    if (RT_EOK != rt_mb_recv(*mbox, (rt_ubase_t *)*msg, 0))
    {
        return SYS_MBOX_EMPTY;
    }
    else
    {
        return 0;
    }
}

/**
 * @ingroup sys_mbox
 * Deallocates a mailbox. If there are messages still present in the
 * mailbox when the mailbox is deallocated, it is an indication of a
 * programming error in lwIP and the developer should be notified.
 * 
 * @param mbox mbox to delete
 */
void sys_mbox_free(sys_mbox_t *mbox)
{
    LWIP_ASSERT(("mbox != NULL"), mbox);

    if (RT_EOK != rt_mb_delete(*mbox))
    {
        LWIP_DEBUGF(NETIF_DEBUG, ("mbox delete fail.\r\n"));
    }
}

/**
 * @ingroup sys_mbox
 * Returns 1 if the mailbox is valid, 0 if it is not valid.
 * When using pointers, a simple way is to check the pointer for != NULL.
 * When directly using OS structures, implementing this may be more complex.
 * This may also be a define, in which case the function is not prototyped.
 */
int sys_mbox_valid(sys_mbox_t *mbox)
{
    if (NULL != *mbox)
    {
        return 1;
    }
    return 0;
}

/**
 * @ingroup sys_mbox
 * Invalidate a mailbox so that sys_mbox_valid() returns 0.
 * ATTENTION: This does NOT mean that the mailbox shall be deallocated:
 * sys_mbox_free() is always called before calling this function!
 * This may also be a define, in which case the function is not prototyped.
 */
void sys_mbox_set_invalid(sys_mbox_t *mbox)
{
    LWIP_ASSERT(("mbox != NULL"), mbox);

    *mbox = NULL;
}

/**
 * @ingroup sys_misc
 * The only thread function:
 * Starts a new thread named "name" with priority "prio" that will begin its
 * execution in the function "thread()". The "arg" argument will be passed as an
 * argument to the thread() function. The stack size to used for this thread is
 * the "stacksize" parameter. The id of the new thread is returned. Both the id
 * and the priority are system dependent.
 * ATTENTION: although this function returns a value, it MUST NOT FAIL (ports have to assert this!)
 * 
 * @param name human-readable name for the thread (used for debugging purposes)
 * @param thread thread-function
 * @param arg parameter passed to 'thread'
 * @param stacksize stack size in bytes for the new thread (may be ignored by ports)
 * @param prio priority of the new thread (may be ignored by ports) */
sys_thread_t sys_thread_new(const char *name, lwip_thread_fn thread, void *arg, int stacksize, int prio)
{
    rt_uint32_t tick = 10; /* 定义任务时间片大小 */
    sys_thread_t id;
    rt_err_t err;

    LWIP_ASSERT(("name != NULL"), name);
    LWIP_ASSERT(("thread != NULL"), thread);

    id = rt_thread_create(name, thread, arg, stacksize, prio % RT_THREAD_PRIORITY_MAX, tick);

    LWIP_ASSERT("id != NULL", id);

    err = rt_thread_startup(id);
    LWIP_ASSERT(("thread startup fail"), RT_EOK == err);
    return id;
}

/**
 * 返回系统启动后到当前时间的滴答计数值，单位为毫秒，
 * 不需要考虑计数溢出的问题，这个数值只是用来获取时间的差值。
 * 不实现这个函数意味着你无法使用某些模块功能
 * （比如TCP协议、时间戳、以及NO_SYS为1时的内部超时机制）
 */
u32_t sys_now(void)
{
#if NO_SYS
    return HAL_GetTick(); /* 直接返回HAL库的滴答计时数值 */
#else
    return rt_tick_get(); /* 直接返回操作系统的滴答计时数值 */
#endif /* NO_SYS */
}
